//
//  CGPriceTool.m
//  caogetest
//
//  Created by imax on 2017/7/24.
//  Copyright © 2017年 CaoGe. All rights reserved.
//价格精确计算

#import "CGPriceTool.h"

@implementation CGPriceTool



+(NSString *)setCorrectNum:(NSString*)tempString
{
    //先判断第一位是不是 . ,是 . 补0
    if (tempString.floatValue <= 0) {
        tempString = @"0.00";
    }
    //判断字符串是否包含 .
    if ([tempString containsString:@"."]) {
        //取得 . 的位置
        NSRange pointRange = [tempString rangeOfString:@"."];
        //判断 . 后面有几位
        NSUInteger f = tempString.length - 1 - pointRange.location;
        //如果大于2位就截取字符串保留两位,如果小于两位,直接截取
        if (f == 1) {
            tempString = [NSString stringWithFormat:@"%@%@",tempString,@"0"];
        }
    }else{
        tempString = [NSString stringWithFormat:@"%@%@",tempString,@".00"];
    }
    return tempString;
}

+ (NSString *)decimalNumberCalucate:(NSString *)originValue1 originValue2:(NSString *)originValue2 calucateWay:(calucateWay)calucateWay
{
    NSDecimalNumberHandler * hander = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    
    //保留两位小数（scale）
    NSDecimalNumber *decimalNumber1 = [NSDecimalNumber decimalNumberWithString:originValue1];
    NSDecimalNumber *decimalNumber2 = [NSDecimalNumber decimalNumberWithString:originValue2];
    NSDecimalNumber *product;
    switch (calucateWay) {
        case Adding:
            product = [decimalNumber1 decimalNumberByAdding:decimalNumber2 withBehavior:hander];
            break;
            
        case Subtracting:
            product = [decimalNumber1 decimalNumberBySubtracting:decimalNumber2];
            break;
            
        case Multiplying:
            product = [decimalNumber1 decimalNumberByMultiplyingBy:decimalNumber2];
            break;
            
        case Dividing:
            product = [decimalNumber1 decimalNumberByDividingBy:decimalNumber2];
            break;
            
        default:
            break;
    }
    return [product stringValue];
}

@end
